// Copyright 2020 autocareai.com. All rights reserved.
// Use of this source code is governed by autocareai.com.

package dao

import (
	"fmt"

	"fawn/blog/models"
	"fawn/blog/parames"

	"github.com/jinzhu/gorm"
	"go.uber.org/zap"
)

var ArticleDao = newArticleDao()

type articleDao struct{}

func newArticleDao() *articleDao {
	return &articleDao{}
}

func (d *articleDao) TableName() string {
	return "t_article"
}

// 获取详情
func (d *articleDao) Info(db *gorm.DB, id int) (info models.Article, next, last parames.ArticleNext, err error) {
	err = db.Table(d.TableName()).Where("id = ?", id).First(&info).Error
	if err != nil {
		l.Error("mysql",
			zap.String("sql", fmt.Sprintf("%+v", db.QueryExpr())),
			zap.String("error", err.Error()))
		return info, next, last, err
	}
	hdb := db.Table(d.TableName()).Select("id,title")
	err = hdb.Where("id > ?", id).Order("id desc").Limit(1).Find(&next).Error
	err = hdb.Where("id < ?", id).Order("id desc").Limit(1).Find(&last).Error

	return info, next, last, nil
}

// 获取文章列表
func (d *articleDao) List(db *gorm.DB, limit, offset int) (list []models.Article, count int, err error) {
	slider := db.Table(d.TableName())
	err = slider.Table(d.TableName()).Order("id desc").Limit(limit).Offset(offset).Find(&list).Error
	if err != nil {
		l.Error("mysql",
			zap.String("sql", fmt.Sprintf("%+v", db.QueryExpr())),
			zap.String("error", err.Error()))
		return nil, 0, err
	}

	err = slider.Count(&count).Error
	if err != nil {
		l.Error("mysql", zap.String("error", err.Error()))
		return nil, 0, err
	}

	return list, count, nil
}

// 置顶
func (d *articleDao) Top(db *gorm.DB) (info models.Article, err error) {
	err = db.Table(d.TableName()).Where("top = 1").First(&info).Error
	if err != nil {
		l.Error("mysql",
			zap.String("sql", fmt.Sprintf("%+v", db.QueryExpr())),
			zap.String("error", err.Error()))
		return info, err
	}

	return info, nil
}
